package cn.lanqiao.bigDate.service.excle;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * Created by posy on 18.1.2.
 * excel服务
 */
@Component
public class ExcelService {
	/**
	 * 获取Excel，将数据转换成 List<T> 的模式
	 * Excel 数据要求第一行为对象的属性名称
	 *
	 * @param sheetName sheet名称
	 * @param tClass    要转换成的实体类
	 * @param <T>
	 * @return List对象数组
	 * @throws IOException
	 */
	public static <T> List<T> readExcelOfList(InputStream inputStream, String sheetName, Class<T> tClass) throws IOException, InvalidFormatException {
		List<String> resultMapList = new ArrayList<>();

		// 应用工厂模式 依据文件扩展名 创立对应的Workbook
		Workbook workbook = WorkbookFactory.create(inputStream);
		Sheet sheet = workbook.getSheet(sheetName);
		int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
		JSONObject jsonObject;
		Map<String, Object> resultMap;
		List<Map<String,Object>> list = new ArrayList<>();
		for (int i = 1; i < rowCount + 1; i++) {
			Row row = sheet.getRow(i);
			resultMap = new HashMap<>();
			for (int j = 0; j < row.getLastCellNum(); j++) {
				if (row.getCell(j)==null){
					continue;
				}
					row.getCell(j).setCellType(CellType.STRING);
					resultMap.put(sheet.getRow(0).getCell(j).toString(), row.getCell(j)+"");
				}

			list.add(resultMap);

		}
		return getListObject(list,tClass);
	}

	public static <T> List<T> getListObject(List<Map<String,Object>> list,Class<T> cls){
		List<T> paramList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(list)){
			for (Map<String, Object> map : list) {
				paramList.add(parseMapObject(map,cls));
			}
		}
		return paramList;
	}

	public static <T> T parseMapObject(Map<String,Object> paramMap, Class<T> cls) {
		String str="";
		try {
			str= JSONObject.toJSONString(paramMap);

		}catch (Exception e){
			e.printStackTrace();
		}
		T data= JSONObject.parseObject(str, cls);
		return data;
	}

}